package com.uduemc.biso.node.web.component.html;

import java.io.StringWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.velocity.Template;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;

import com.uduemc.biso.node.core.common.entities.SiteContainer;
import com.uduemc.biso.node.core.common.udinpojo.ContainerCustomData;
import com.uduemc.biso.node.core.utils.ComponentUtil;
import com.uduemc.biso.node.web.component.html.inter.HIContainerUdin;

@Component
public class HContainerCustomUdin implements HIContainerUdin {

	private static String name = "container_custom";

	@Autowired
	private BasicUdin basicUdin;

	public Template getTemplate(String theme) {
		return basicUdin.getTemplate(name, theme);
	}

	@Override
	public StringBuilder html(SiteContainer siteContainer, List<StringBuilder> childrenHtml) {
		StringBuilder stringBuilder = new StringBuilder();
		String config = siteContainer.getSContainer().getConfig();
		ContainerCustomData containerCustomData = ComponentUtil.getConfig(config, ContainerCustomData.class);
		if (containerCustomData == null || StringUtils.isEmpty(containerCustomData.getTheme())) {
			return stringBuilder;
		}
		String id = "custom-id-" + DigestUtils.md5DigestAsHex(String.valueOf(siteContainer.getSContainer().getId()).getBytes());

		String style = containerCustomData.getStyle();

		// + childrenHtml.toString()
		Map<String, Object> mapData = new HashMap<>();
		mapData.put("conid", siteContainer.getSContainer().getId());
		mapData.put("id", id);

		mapData.put("style", style);

		mapData.put("html", basicUdin.getCildrenHtml(childrenHtml));

		StringWriter render = basicUdin.render(name, "custom_" + containerCustomData.getTheme(), mapData);
		stringBuilder.append(render);
		return stringBuilder;
	}

}
